import { useRequest } from 'ahooks';
import {
  Button, Form, Input, message
} from 'antd';
import { useHistory } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { FC } from 'react';
import { InfoCircleOutlined } from '@ant-design/icons';

import * as APIS from '../../../../constants/api-constants';
import useHandleCountBackwards from '../../hooks';
import {
  initUserUuidAction,
  initScoreListAction,
  initMergeUuidAction,
  clearUserAction
} from '../../actions';

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};

const SMS: FC<{ questionnaireUuid: string }> = ({ questionnaireUuid }) => {
  const [form] = Form.useForm();
  const history = useHistory();
  const dispatch = useDispatch();
  /**
   * 发送验证码
   */
  const { run } = useRequest((tel: string) => ({
    url: APIS.SMS,
    method: 'GET',
    params: { tel }
  }), {
    manual: true,
    onSuccess: (res) => {
      const { sendMessageStatus } = res.data.existResult;

      if (!sendMessageStatus) {
        message.error('不可60s内连续验证');
      }
    },
    onError: () => {
      console.log('获取失败');
    }
  });
  const {
    handleCountBackwards,
    count,
    isTiming
  } = useHandleCountBackwards(() => {
    run(form.getFieldValue('tel'));
  }, () => { });

  /**
   * 校验验证码
   */
  const {
    run: requestSMSCodeValidate,
    loading: SMSCodeValidateLoading
  } = useRequest((
    tel: string,
    code: string,
    uuid: string
  ) => ({
    url: APIS.SMS_VERIFY,
    method: 'GET',
    params: {
      tel,
      code,
      questionnaireUuid: uuid
    }
  }), {
    manual: true,
    onSuccess: (res) => {
      const result = res.data;

      if (!result?.verifyMessageState) {
        message.error('短信验证失败');
        return;
      }

      // 成功之后需要根据 process 跳转到不同页面
      const {
        answerProgressState,
        currentQuestion,
        userUuid,
        mergeUuid,
        scoreList
      } = result;
      // 验证失败或者用户未注册基本信息时，初始化undefined数组
      if (!scoreList) {
        const initBasicScoreList = [];
        for (let index = 0; index < 62; index += 1) {
          initBasicScoreList.push({ questionId: index + 1 });
        }
        dispatch(initScoreListAction(initBasicScoreList));
      } else {
        dispatch(initScoreListAction(scoreList));
      }

      dispatch(clearUserAction());
      dispatch(initUserUuidAction(userUuid));
      dispatch(initMergeUuidAction(mergeUuid));
      switch (answerProgressState) {
        case 0:
          history.push(`/questionAnswer/home/${questionnaireUuid}/closeResult`);
          break;
        case 1:
          history.push(`/questionAnswer/home/${questionnaireUuid}/basicInfo/${0}`);
          break;
        case 2:
          history.push(`/questionAnswer/home/${questionnaireUuid}/question/${0}`);
          break;
        case 3:
          history.push(`/questionAnswer/home/${questionnaireUuid}/question/${currentQuestion}`);
          break;
        case 4:
          history.push(`/questionAnswer/home/${questionnaireUuid}/successResult`);
          break;
        default:
          history.push(`/questionAnswer/home/${questionnaireUuid}/closeResult`);
      }
    },
    onError: () => {
      message.error('短信验证失败');
    }
  });

  return (
    <Form
      form={form}
      {...formItemLayout}
      onFinish={(values) => {
        requestSMSCodeValidate(
          values.tel,
          values.code,
          questionnaireUuid
        );
      }}
    >
      <Form.Item
        name="tel"
        validateTrigger={['onBlur']}
        rules={[
          {
            message: '请输入正确的手机号',
            pattern: new RegExp(
              /^1([3578][0-9]|4[579]|66|7[0135678]|9[89])[0-9]{8}$/
            ),
          },
          {
            required: true,
            message: '请输入手机号',
          },
          { validateTrigger: 'onBlur' }
        ]}
      >
        <Input
          placeholder="请输入手机号"
          suffix={(
            <Button
              type="link"
              onClick={() => {
                form.validateFields(['tel']).then(() => {
                  handleCountBackwards();
                }).catch(() => {
                  // message.error('请输入正确的手机');
                });
              }}
              disabled={isTiming}
            >
              {isTiming ? `剩余${count}s` : '获取验证码'}
            </Button>
          )}
        />
      </Form.Item>

      <Form.Item
        name="code"
        rules={[{
          required: true,
          message: '请输入验证码',
        }]}
      >
        <Input
          placeholder="验证码"
          suffix={(
            <Button type="link">
              <InfoCircleOutlined style={{ color: 'rgba(0, 0, 0, 0.45)' }} />
            </Button>
          )}
        />
      </Form.Item>
      <Form.Item>
        <Button
          type="primary"
          style={{
            width: '100%'
          }}
          loading={SMSCodeValidateLoading}
          size="large"
          onClick={() => {
            form.submit();
          }}
        >
          验证
        </Button>
      </Form.Item>
    </Form>
  );
};

export default SMS;
